package com.example.myprojectoffeixue;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
public class MyYaoKongActivity extends Activity {

    private ListView lv;
    private ListView lv1;
    private ListView lv2;
    private ArrayList<controllerList> parseArray;
    private YaoKongAdpter y;
    private YaoKongAdpter y1;
    private YaoKongAdpter y2;
    private TextView tv1;
    private TextView tv2;
    private TextView tv3;
    MyApplication m;
    public String name;
    private ArrayList<controllerList> TVlist = new ArrayList<>();
    private ArrayList<controllerList> KTlist = new ArrayList<>();
    private ArrayList<controllerList> JDHlist = new ArrayList<>();
    private LinearLayout ivjh;
    SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_yao_kong);

    }
    @Override
    protected void onStart() {
        sp = getSharedPreferences("first", MODE_PRIVATE);
        info();
        super.onStart();
    }
    private void info() {
        TVlist.clear();
        KTlist.clear();
        JDHlist.clear();
        m = (MyApplication) getApplication();
        ivjh = (LinearLayout) findViewById(R.id.lin_myyaokongqi);
        if(!ivjh.isShown()){
            ivjh.setVisibility(View.VISIBLE);
        }
        TextView addtv = (TextView) findViewById(R.id.add_myyaokong);
        addtv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!MyApplication.localflag){
                Intent it = new Intent(MyYaoKongActivity.this, AddHongWaiSheBeiActivity.class);
                startActivity(it);}else{
                    ToastUtils.showToast(getBaseContext(),"当前环境下不支持添加遥控器");
                }
            }
        });


        lv = (ListView) findViewById(R.id.lv_myykq);
        lv1 = (ListView) findViewById(R.id.lv1_myykq);
        lv2 = (ListView) findViewById(R.id.lv2_myykq);

        setListViewHeightBasedOnChildren(lv);
        setListViewHeightBasedOnChildren(lv1);
        setListViewHeightBasedOnChildren(lv2);


        tv1 = (TextView) findViewById(R.id.KT_yaokong);
        tv3 = (TextView) findViewById(R.id.JDH_yaokong);
        tv2 = (TextView) findViewById(R.id.TV_yaokong);
        LinearLayout iv = (LinearLayout) findViewById(R.id.iv_myyaokongqi);

        iv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();

            }
        });

        if(!MyApplication.localflag) {
            GateWay gt = new GateWay();
            gt.devices = new ArrayList<SheBeiClass>();
            SheBeiClass sb = new SheBeiClass();
            sb.ieee = m.ieee_ykq;
            sb.port = m.port_ykq;
            gt.devices.add(sb);
            String j = JSON.toJSONString(gt);
            Log.d("cmd", j);
            j = AESUtil.encrypt(j);
            HttpUtils httpUtils = new HttpUtils();
            RequestParams params = new RequestParams();
            params.setHeader("Content-Type", "application/json");
            try {
                params.setBodyEntity(new StringEntity(j, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            httpUtils.send(HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/remote/loadController", params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            HttpConnection.showToast(getBaseContext(), "网络异常");
                            ivjh.setVisibility(View.GONE);
                            tv1.setVisibility(View.GONE);
                            tv2.setVisibility(View.GONE);
                            tv3.setVisibility(View.GONE);
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> arg0) {
                            Log.d("fffffffffff", "jjjjjjjjjj");
                            if (arg0.result != null && !("".equals(arg0.result))) {
                                arg0.result = AESUtil.decrypt(arg0.result);
                                Log.d("ffffffffffff", arg0.result);
                                JSONObject j = JSONObject.parseObject(arg0.result);
                                String status = j.getString("status");
                                if ("0".equals(status)) {
                                    JSONArray j1 = j.getJSONArray("controllerList");
                                    sp.edit().putString("controllerList",j1.toString()).commit();
                                    Log.d("存进去",j1.toString());
                                    parseArray = (ArrayList<controllerList>) JSONArray.parseArray(j1.toString(), controllerList.class);
                                    for (int i = 0; i < parseArray.size(); i++) {
                                        if ("04".equals(parseArray.get(i).kind)) {
                                            TVlist.add(parseArray.get(i));
                                        } else if ("02".equals(parseArray.get(i).kind)) {
                                            JDHlist.add(parseArray.get(i));
                                        } else if ("06".equals(parseArray.get(i).kind)) {
                                            KTlist.add(parseArray.get(i));
                                        }
                                    }
                                    if (KTlist.size() == 0) {
                                        tv1.setVisibility(View.GONE);
                                    } else {
                                        tv1.setVisibility(View.VISIBLE);
                                    }
                                    if (TVlist.size() == 0) {
                                        tv2.setVisibility(View.GONE);
                                    } else {
                                        tv2.setVisibility(View.VISIBLE);
                                    }
                                    if (JDHlist.size() == 0) {
                                        tv3.setVisibility(View.GONE);
                                    } else {
                                        tv3.setVisibility(View.VISIBLE);
                                    }
                                    y = new YaoKongAdpter(KTlist, getBaseContext());
                                    y1 = new YaoKongAdpter(TVlist, getBaseContext());
                                    y2 = new YaoKongAdpter(JDHlist, getBaseContext());
                                    lv.setAdapter(y);
                                    lv1.setAdapter(y1);
                                    lv2.setAdapter(y2);
                                    ivjh.setVisibility(View.GONE);
                                } else {
                                    HttpConnection.showToast(MyYaoKongActivity.this, "服务器错误");

                                }
                            } else {
                                HttpConnection.showToast(MyYaoKongActivity.this, "服务器错误");
                            }
                        }
                    });
        }else{

            String controllerList=sp.getString("controllerList",null);
            Log.d("内部取出1111111111111","内部");

            if(controllerList!=null){
                Log.d("内部取出","内部");
                parseArray = (ArrayList<controllerList>) JSONArray.parseArray(controllerList, controllerList.class);
                for (int i = 0; i < parseArray.size(); i++) {
                    if ("04".equals(parseArray.get(i).kind)) {
                        TVlist.add(parseArray.get(i));
                    } else if ("02".equals(parseArray.get(i).kind)) {
                        JDHlist.add(parseArray.get(i));
                    } else if ("06".equals(parseArray.get(i).kind)) {
                        KTlist.add(parseArray.get(i));
                    }
                }
                if (KTlist.size() == 0) {
                    tv1.setVisibility(View.GONE);
                } else {
                    tv1.setVisibility(View.VISIBLE);
                }
                if (TVlist.size() == 0) {
                    tv2.setVisibility(View.GONE);
                } else {
                    tv2.setVisibility(View.VISIBLE);
                }
                if (JDHlist.size() == 0) {
                    tv3.setVisibility(View.GONE);
                } else {
                    tv3.setVisibility(View.VISIBLE);
                }
                y = new YaoKongAdpter(KTlist, getBaseContext());
                y1 = new YaoKongAdpter(TVlist, getBaseContext());
                y2 = new YaoKongAdpter(JDHlist, getBaseContext());
                lv.setAdapter(y);
                lv1.setAdapter(y1);
                lv2.setAdapter(y2);
            }
            ivjh.setVisibility(View.GONE);
        }
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                m.type="06";
                Intent it = new Intent(MyYaoKongActivity.this, HwKTActivity.class);
                it.putExtra("controllerList", KTlist.get(position));
                startActivity(it);
            }

        });

        lv1.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                m.type="04";
                Intent it = new Intent(MyYaoKongActivity.this, YaoKongQActivity.class);
                it.putExtra("controllerList", TVlist.get(position));
                startActivity(it);

            }
        });


        lv2.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                m.type="02";
                Intent it = new Intent(MyYaoKongActivity.this, JidingHeActivity.class);
                it.putExtra("controllerList", JDHlist.get(position));
                startActivity(it);
            }
        });

        lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            Dialog dialog;

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                dialog = new Dialog(MyYaoKongActivity.this,R.style.dialog);
                dialog.setContentView(R.layout.yaokongqidialog);
                TextView iv1 = (TextView) dialog.findViewById(R.id.iv1_mydialog);
                iv1.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();

                TextView tv = (TextView) dialog.findViewById(R.id.delete);
                TextView tv1 = (TextView) dialog.findViewById(R.id.restudy);
                tv1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int controllerId = KTlist.get(position).id;
                        int selfLearning = KTlist.get(position).selfLearning;
                        Intent it = new Intent(MyYaoKongActivity.this, HongWStudyActivity.class);
                        m.type = "06";
                        it.putExtra("id", controllerId);
                        it.putExtra("selfLearning", selfLearning + "");

                        if (!"06".equals(m.type)) {
                            ArrayList<String> button = new ArrayList<String>();
                            ArrayList<String> code = new ArrayList<String>();
                            ArrayList<controllerDetail> controllerDetail = KTlist.get(position).controllerDetail;
                            for (int i = 0; i < controllerDetail.size(); i++) {
                                button.add(controllerDetail.get(i).button + "");
                                code.add(controllerDetail.get(i).originalCode);
                            }
                            it.putExtra("name", KTlist.get(position).name);
                            it.putStringArrayListExtra("button", button);
                            it.putStringArrayListExtra("code", code);

                        }
                        startActivity(it);
                        dialog.dismiss();
                        finish();


                    }
                });

                tv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int controllerId = KTlist.get(position).id;
                        controllerDetail c = new controllerDetail();
                        c.controllerId = controllerId;
                        String j = JSON.toJSONString(c);
                        j = AESUtil.encrypt(j);
                        HttpUtils httpUtils = new HttpUtils();
                        RequestParams params = new RequestParams();
                        params.setHeader("Content-Type", "application/json");
                        try {
                            params.setBodyEntity(new StringEntity(j, "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        httpUtils.send(HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/remote/deleteController",
                                params, new RequestCallBack<String>() {

                                    @Override
                                    public void onFailure(HttpException arg0, String arg1) {
                                        HttpConnection.showToast(getBaseContext(),"网络异常");

                                    }

                                    @Override
                                    public void onSuccess(ResponseInfo<String> arg0) {
                                        if(arg0.result != null && !("".equals(arg0.result))){
                                        arg0.result = AESUtil.decrypt(arg0.result);
                                        JSONObject j = JSONObject.parseObject(arg0.result);
                                        Integer it = j.getInteger("status");
                                        if (0 == it) {
                                            if (KTlist.size() != 0) {
                                                KTlist.remove(position);
                                                dialog.dismiss();
                                                y.notifyDataSetChanged();
                                            }
                                        }
                                    }else{

                                            HttpConnection.showToast(getBaseContext(),"服务器错误");
                                        }
                                    }
                                });

                    }
                });

                return true;

            }

        });


        lv1.setOnItemLongClickListener(new OnItemLongClickListener() {
            Dialog dialog;

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                dialog = new Dialog(MyYaoKongActivity.this,R.style.dialog);
                dialog.setContentView(R.layout.yaokongqidialog);

                TextView iv1 = (TextView) dialog.findViewById(R.id.iv1_mydialog);
                iv1.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();

                TextView tv = (TextView) dialog.findViewById(R.id.delete);
                TextView tv1 = (TextView) dialog.findViewById(R.id.restudy);
                tv1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int controllerId = TVlist.get(position).id;
                        int selfLearning = TVlist.get(position).selfLearning;
                        Intent it = new Intent(MyYaoKongActivity.this, HongWStudyActivity.class);
                        m.type = "04";
                        it.putExtra("id", controllerId);
                        it.putExtra("selfLearning", selfLearning + "");
                        if (!"06".equals(m.type)) {
                            ArrayList<String> button = new ArrayList<String>();
                            ArrayList<String> code = new ArrayList<String>();
                            ArrayList<controllerDetail> controllerDetail = TVlist.get(position).controllerDetail;
                            for (int i = 0; i < controllerDetail.size(); i++) {
                                button.add(controllerDetail.get(i).button + "");
                                code.add(controllerDetail.get(i).originalCode);
                            }
                            it.putExtra("name", TVlist.get(position).name);
                            it.putStringArrayListExtra("button", button);
                            it.putStringArrayListExtra("code", code);

                        }
                        startActivity(it);
                        dialog.dismiss();
                        finish();
                    }
                });

                tv.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        int controllerId = TVlist.get(position).id;
                        controllerDetail c = new controllerDetail();
                        c.controllerId = controllerId;

                        String j = JSON.toJSONString(c);
                        j = AESUtil.encrypt(j);
                        HttpUtils httpUtils = new HttpUtils();
                        RequestParams params = new RequestParams();
                        params.setHeader("Content-Type", "application/json");
                        try {
                            params.setBodyEntity(new StringEntity(j, "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        httpUtils.send(HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/remote/deleteController",
                                params, new RequestCallBack<String>() {

                                    @Override
                                    public void onFailure(HttpException arg0, String arg1) {
                                        HttpConnection.showToast(getBaseContext(),"网络异常");

                                    }

                                    @Override
                                    public void onSuccess(ResponseInfo<String> arg0) {
                                        if (arg0.result != null && !("".equals(arg0.result))) {
                                            arg0.result = AESUtil.decrypt(arg0.result);

                                            JSONObject j = JSONObject.parseObject(arg0.result);
                                            Integer it = j.getInteger("status");
                                            if (0 == it) {
                                                if (TVlist.size() != 0) {
                                                    TVlist.remove(position);
                                                    dialog.dismiss();
                                                    y1.notifyDataSetChanged();
                                                }

                                            }
                                        } else {

                                            HttpConnection.showToast(getBaseContext(),"服务器错误");
                                        }
                                    }
                                });

                    }
                });

                return true;

            }

        });


        lv2.setOnItemLongClickListener(new OnItemLongClickListener() {
            Dialog dialog;

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                dialog = new Dialog(MyYaoKongActivity.this,R.style.dialog);
                dialog.setContentView(R.layout.yaokongqidialog);

                TextView iv1 = (TextView) dialog.findViewById(R.id.iv1_mydialog);
                iv1.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();

                    }
                });
                dialog.show();

                TextView tv = (TextView) dialog.findViewById(R.id.delete);
                TextView tv1 = (TextView) dialog.findViewById(R.id.restudy);
                tv1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int controllerId = JDHlist.get(position).id;
                        int selfLearning = JDHlist.get(position).selfLearning;
                        Intent it = new Intent(MyYaoKongActivity.this, HongWStudyActivity.class);
                        m.type = "02";
                        it.putExtra("id", controllerId);
                        it.putExtra("selfLearning", selfLearning + "");
                        if (!"06".equals(m.type)) {
                            ArrayList<String> button = new ArrayList<String>();
                            ArrayList<String> code = new ArrayList<String>();
                            ArrayList<controllerDetail> controllerDetail = JDHlist.get(position).controllerDetail;
                            for (int i = 0; i < controllerDetail.size(); i++) {
                                button.add(controllerDetail.get(i).button + "");
                                code.add(controllerDetail.get(i).originalCode);
                            }
                            it.putExtra("name", JDHlist.get(position).name);
                            it.putStringArrayListExtra("button", button);
                            it.putStringArrayListExtra("code", code);

                        }
                        startActivity(it);
                        dialog.dismiss();
                        finish();


                    }
                });


                tv.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {


                        int controllerId = JDHlist.get(position).id;
                        controllerDetail c = new controllerDetail();
                        c.controllerId = controllerId;

                        String j = JSON.toJSONString(c);
                        j = AESUtil.encrypt(j);
                        HttpUtils httpUtils = new HttpUtils();
                        RequestParams params = new RequestParams();
                        params.setHeader("Content-Type", "application/json");
                        try {
                            params.setBodyEntity(new StringEntity(j, "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        httpUtils.send(HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/remote/deleteController",
                                params, new RequestCallBack<String>() {

                                    @Override
                                    public void onFailure(HttpException arg0, String arg1) {
                                        HttpConnection.showToast(getBaseContext(),"网络异常");
                                    }

                                    @Override
                                    public void onSuccess(ResponseInfo<String> arg0) {
                                        if(arg0.result != null && !("".equals(arg0.result))){
                                        arg0.result = AESUtil.decrypt(arg0.result);

                                        JSONObject j = JSONObject.parseObject(arg0.result);
                                        Integer it = j.getInteger("status");
                                        if (0 == it) {
                                            if (JDHlist.size() != 0) {
                                                JDHlist.remove(position);
                                                dialog.dismiss();
                                                y2.notifyDataSetChanged();
                                            }

                                        }
                                    }else{

                                            HttpConnection.showToast(getBaseContext(),"服务器错误");

                                    }}

                                });

                    }
                });

                return true;

            }

        });


    }


    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }


}
